'''
Created on Apr 12, 2012

@author: Galvez, Martino, Ventura
'''
from pyevolve import G1DList

from pyevolve import GSimpleGA

from pyevolve import Mutators

# This function is the evaluation function, we want
# to give high score to more zero'ed chromosomes
def eval_func(chromosome):
    import sys
    sys.path.append("C:\\vs2010 workspace\\Projects\\Lib\\Lib\\Agente")
    sys.path.append("C:\\vs2010 workspace\\Projects\\Lib\\Lib\\Agente\\Framework")
    import itertools, random, collections
    from time import time

    from Kosong import Kosong
    from _agents import RandomAgent, FileAgent
    from _base import run_match, match
    from Agente import MiniMaxObligatorio
    from _agents import MiniMaxAgent

    import _contests
    from _contests import AllAgainstAll_Contest
    from _contests import Stats
    from _contests import complete

    # Diccionario que contiene las diferentes fichas con sus valores, estos valores se iran ajustando
    parametros = {'0':0, 'a':chromosome[0], 'A':chromosome[0], 'b':chromosome[1], 'B':chromosome[1], 'c':chromosome[2], 'C':chromosome[2]}
        
    # Cantidad de partidas a jugar para obtener el muestreo
    cantMuestreo = 3
    h = 2
    # Variable que almacena la cantidad de partidas ganadas contra las perdidas
    score = 0

    
    #rnd = random.Random()
    ## Crea la lista de agentes a utilizar
    agenteRef = MiniMaxAgent(name='Random', horizon= h)
    agentes = [agenteRef]
    agenteEvol = MiniMaxObligatorio(name='NuestroAgente', heuristic=MiniMaxObligatorio.__heuristic__, params=parametros, horizon= h)
    agentes.extend([agenteEvol])
   
    a = AllAgainstAll_Contest(Kosong(), agentes, cantMuestreo)
    stats = complete(a)
    f = open('C:\\Users\\Fede\\Documents\\Facultad\\IA\\Obligatorio\\Lib\\salida.txt', 'a')
    f.write('a,b,c\n')
    f.write(str(parametros['a']) + ',' + str(parametros['b']) + ',' + str(parametros['c']) + '\n')  
    #log = a.log()
    s = stats.__str__()
    f.write(s)
    f.write('\n')
    f.close()
    won  = stats.matches_won
    lost = stats.matches_lost
    resutladoEval = won[agenteEvol] - lost[agenteEvol] + (cantMuestreo * 2)
    print('evaluacion de A=' + str(parametros['a']) + ',B=' + str(parametros['b']) + ',C=' + str(parametros['c']))
    print('Resultado: ' + str(resutladoEval))
    # retorno la cantidad de partidos ganados menos la cantidad de partidos perdidos
    return resutladoEval

#  Genome instance, set the size of the list
genome = G1DList.G1DList(3)

# The evaluator function (objective function)
genome.evaluator.set(eval_func)
# The possible values that each letter in the cromosome can take
genome.setParams(rangemin=0, rangemax=10)
# Change type of mutator
genome.mutator.set(Mutators.G1DListMutatorIntegerRange)

ga = GSimpleGA.GSimpleGA(genome)   
# Set number of generations
ga.setGenerations(10)
# Set size of the population
ga.setPopulationSize(10)
# Set mutation rate
ga.setMutationRate(0.05)

# Do the evolution, with stats dump
# frequency of 10 generations
ga.evolve(freq_stats=1)

# Best individual
resultados = ga.bestIndividual()
salida = ''
salida += 'a/A: ' 
salida += chr(resultados[0])
salida += '/n'
salida += 'b/B: ' 
salida += chr(resultados[1])
salida += '/n'
salida += 'c/C: ' 
salida += chr(resultados[2])
salida += '/n'
print salida
print '##################### FINAL #####################'

